package datastructure.search;

/**
 * 二分查找法
 * @author lbw
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 9, 11, 12, 34, 80};
        System.out.println(binarySearch(arr, 0, arr.length - 1, -1));
    }

    public static int binarySearch(int[] arr, int left, int right, int target){
        if (arr[left] > target || arr[right] < target || left > right){
            return -1;
        }
        int mid = left + (right - left) / 2;
        if (arr[mid] > target){
            //向左递归
            return binarySearch(arr, left, mid - 1, target);
        } else if (arr[mid] < target){
            //向右递归
            return binarySearch(arr, mid + 1, right, target);
        } else {
            return mid;
        }
    }
}
